package com.mohunhun.services.impl;

import com.mohunhun.common.AppResult;
import com.mohunhun.common.ResultCode;
import com.mohunhun.dao.UserMapper;
import com.mohunhun.exception.ApplicationException;
import com.mohunhun.model.Board;
import com.mohunhun.model.User;
import com.mohunhun.services.IUserService;
import com.mohunhun.utils.MD5Util;
import com.mohunhun.utils.StringUtil;
import com.mohunhun.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void creatNormalUser(User user) {

        // 参数非空校验
        if (user == null
                || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 按用户名查询用户信息
        User exisitsUser = userMapper.selectByUserName(user.getUsername());
        // 判断用户是否存在
        if (exisitsUser != null) {
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 新增用户,设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        // 写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        log.info(ResultCode.SUCCESS_CREATE.toString() + ",username=" + user.getUsername());

    }

    @Override
    public User selectByUserName(String username) {

        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }


        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        User user = selectByUserName(username);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + ",username=" + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        String encryptPassword = MD5Util.md5(password, user.getSalt());

        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + "，密码错误，username=" + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        log.info("登录成功，username=" + username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",board id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setArticleCount(user.getArticleCount() + 1);

        int row = userMapper.updateByPrimaryKeySelective(newUser);

        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "，受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }


    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",board id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setArticleCount(user.getArticleCount() - 1);

        int row = userMapper.updateByPrimaryKeySelective(newUser);

        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "，受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        // 1. 参数校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 检查用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 3. 构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());

        boolean hasUpdate = false;

        // 4. 用户名校验与更新
        if (!StringUtil.isEmpty(user.getUsername())
                && !Objects.equals(user.getUsername(), existsUser.getUsername())) {
            User existingByUsername = userMapper.selectByUserName(user.getUsername());
            if (existingByUsername != null) {
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            hasUpdate = true;
        }

        // 5. 昵称
        if (!Objects.equals(existsUser.getNickname(), user.getNickname())) {
            updateUser.setNickname(user.getNickname());
            hasUpdate = true;
        }

        if (!Objects.equals(existsUser.getEmail(), user.getEmail())) {
            updateUser.setEmail(user.getEmail());
            hasUpdate = true;
        }

        if (!Objects.equals(existsUser.getPhoneNum(), user.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            hasUpdate = true;
        }

        if (!Objects.equals(existsUser.getRemark(), user.getRemark())) {
            updateUser.setRemark(user.getRemark());
            hasUpdate = true;
        }

        // 10. 如果没有任何字段需要更新，直接返回
        if (!hasUpdate) {
            return;
        }

        // 11. 设置更新时间（如有该字段）
        updateUser.setUpdateTime(new Date()); // 假设 User 有 updateTime 字段

        // 12. 执行更新
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void updateAvatarUrlAndHash(Long userId, String newAvatarUrl, String newFileHash) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setAvatarUrl(newAvatarUrl);
        updateUser.setAvatarHash(newFileHash);
        updateUser.setUpdateTime(new Date());

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        String oldEncryptPassword = MD5Util.md5(oldPassword, user.getSalt());

        if (!oldEncryptPassword.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        String salt = UUIDUtil.UUID_32();
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(MD5Util.md5(newPassword, salt));
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }


}

